package eu.fishcode.android.ui.component;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;

import eu.fishcode.android.utils.Utils;

public class FileBrowse extends JPanel implements ActionListener, FocusListener {

	private static final long serialVersionUID = 1111111100000000113L;
	private final JTextField textField;
	private final JFileChooser fileChooser;
	private final JButton btnBrowse;
	private ActionListener actionListener;
	private String strCommand;

	public FileBrowse() {
		this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
		this.setBorder(BorderFactory.createEmptyBorder());
		this.fileChooser = new JFileChooser();
		this.textField = new JTextField();
		this.textField.addFocusListener(this);
		this.btnBrowse = new JButton(Utils.getLabel("browse"));
		this.btnBrowse.addActionListener(this);
		this.add(this.textField);
		this.add(this.btnBrowse);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		this.fileChooser.setSelectedFile(new File(this.getValue()));
		final int returnVal = this.fileChooser.showOpenDialog(this);

		if (returnVal == JFileChooser.APPROVE_OPTION) {
			final File file = this.fileChooser.getSelectedFile();
			if (file != null) {
				this.setFile(file);
				this.actionListener.actionPerformed(new ActionEvent(
						FileBrowse.this, 0, this.strCommand));
			}
		}
	}

	public void addActionListener(ActionListener ai) {
		this.actionListener = ai;
	}

	@Override
	public void focusGained(FocusEvent e) {
	}

	@Override
	public void focusLost(FocusEvent e) {
		this.actionListener.actionPerformed(new ActionEvent(FileBrowse.this, 0,
				this.strCommand));
	}

	public JTextField getTextField() {
		return this.textField;
	}

	public String getValue() {
		return this.textField.getText();
	}

	public void setActionCommand(String command) {
		this.strCommand = command;
	}

	public void setFile(File file) {
		this.setValue(file.getAbsolutePath());
	}

	public void setValue(String value) {
		this.textField.setText(value);
	}

}
